package com.wenx.concurrent.thread;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class VolatileTest implements Runnable {

    volatile Integer count = 0;

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            count++;
        }
    }

    public static void main(String[] args) {
        VolatileTest volatileTest = new VolatileTest();
        List<Thread> collect = IntStream.range(0, 5)
                .mapToObj(i -> {
                    Thread thread = new Thread(volatileTest);
                    return thread;
                }).collect(Collectors.toList());
        collect.forEach(thread -> {
            thread.start();
            //执行完start后立即执行join，会让一个线程执行完成后再执行另一个线程，最后count结果正确
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        });

        //所有线程都先start后再都join，只是等待所有线程都执行完成，导致所有线程++的结果<5000
//        collect.forEach(thread -> {
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });

        System.out.println(volatileTest.count);

    }

}
